<?php

namespace app\admin\controller;

use app\service\role\RoleService;
use app\admin\validate\role\Role as RoleValidate;
use app\model\Role as RoleModel;
use app\model\User as UserModel;
use think\Db;
use think\Exception;

class Role extends BaseController
{
    private static $parentMenu = "role/index";

    /**
     * 角色列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $queryString = $this->request->param('queryString');
        $roleService = new RoleService();
        $list = $roleService->getRoleList($queryString, $this->pageSize);
        $this->assign([
            'queryString' => $queryString,
            'empty' => '<tr><td colspan="7">暂无数据</td></tr>',
            'list' => $list,
            'page' => $list->render()
        ]);
        return $this->fetch('index');
    }

    /**
     * 添加角色
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new RoleValidate();
            $roleService = new roleService();
            $role = $roleService->checkRoleIsExist('admin');
            if (!empty($role) && $data['role_name'] == 'admin') {
                $this->doRedirect('admin' . '会员已存在，不能添加！', '2');
            }
            if (!$validate->check($data)) {
                $this->doRedirect($validate->getError(), '2');
            }
            if (!isset($data['role_status'])) {
                $data['role_status'] = 0;
            }
            $data['create_time'] = time();
            $model = new RoleModel();
            $model->allowField(true)->save($data);
            $this->redirect('role/index');
        }
        $this->assign('parentMenu', self::$parentMenu);
        $this->assign('currentMenu', 'role/index');
        return $this->fetch('add');
    }

    /**
     * 编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $model = new RoleModel();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new RoleValidate();
            if (!$validate->check($data)) {
                $this->doRedirect($validate->getError(), '2');
            }
            if (!isset($data['role_status'])) {
                $data['role_status'] = 0;
            }
            $data['update_time'] = time();
            $model->allowField(true)->save($data, ['role_id' => $data['id']]);
            $this->redirect('role/index');
        }
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->doRedirect('参数错误，请重试！', '2');
        }
        $role = $model->where('role_id', '=', $id)
            ->where('role_status', '<>', -1)
            ->find();
        if (!$role) {
            $this->doRedirect('找不到Id为' . $id . '的数据，请重试！', '2');
        }
        $this->assign('role', $role);
        $this->assign('parentMenu', self::$parentMenu);
        $this->assign('currentMenu', 'role/index');
        return $this->fetch('edit');
    }

    /**
     * 授权
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function authority()
    {
        $model = new RoleModel();
        if ($this->request->isPost()) {
            $selectedId = $this->request->post('selectedId');
            $selectedName = $this->request->post('selectedName');
            $id = $this->request->post('id');
            $model->allowField(true)->save(
                [
                    'role_menu' => $selectedId,
                    'role_menu_name' => $selectedName
                ],
                [
                    'role_id' => $id
                ]
            );
            $this->redirect('role/index');
        }
        $id = $this->request->param('id');
        $role = $model->where('role_id', '=', $id)
            ->where('role_status', '<>', -1)
            ->find();
        if (empty($role)) {
            $this->doRedirect('参数错误，请重试！', '2');
        }
        $result = Db::table('aya_menu')
            ->where('menu_is_admin', '=', 1)
            ->where('menu_status', '=', 1)
            ->order('menu_sort')
            ->order('create_time desc')
            ->field('menu_id as id, menu_parent_id as parentId, menu_name as name')
            ->select();
        foreach ($result as $key => $menu) {
            $result[$key]['open'] = true;
            $idArr = explode(',', $role['role_menu']);
            if (is_array($idArr) && in_array($result[$key]['id'], $idArr)) {
                $result[$key]['checked'] = true;
            }
        }
        $this->assign('tree', json_encode($result));
        $this->assign('id', $id);
        $this->assign('parentMenu', self::$parentMenu);
        $this->assign('currentMenu', 'role/authority');
        return $this->fetch('authority');
    }

    /**
     * 修改状态
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeStatus()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        if (empty($id) || !in_array($status, [-1, 0, 1])) {
            $this->doRedirect('参数错误，请重试！', '2');
        }
        $model = new RoleModel();
        $role = Db::table('aya_role')->where('role_id', '=', $id)
            ->where('role_status', '<>', -1)->find();
        if (!$role) {
            $this->doRedirect('找不到Id为' . $id . '的数据，请重试！', '2');
        }
        if ($role['role_id'] == 1) {
            $this->doRedirect('不能修改超级管理员！', '2');
        }
        $userModel = new UserModel();
        if ($status == -1) { // 若删除角色则把该角色下的用户设置为未有角色状态
            Db::startTrans();
            try {
                $userList = Db::table('aya_user')->where('user_role_id', '=', $role['role_id'])
                    ->where('user_status', '<>', -1)->select();
                if (!empty($userList)) {
                    $list = [];
                    foreach ($userList as $value) {
                        array_push($list, ['user_id' => $value['user_id'], 'role_id' => 0, 'role_name' => '']);
                    }
                    $userModel->saveAll($list);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->doRedirect('操作失败！错误原因为' . $e->getMessage(), '2');
            }
        }
        $model->save(['role_status' => $status], ['role_id' => $id]);
        $this->doRedirect('修改成功！', '1');
    }
}